package com.lgmshare.k3.ui.upgrade;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.widget.Toast;

import com.lgmshare.component.utils.NetworkUtils;
import com.lgmshare.k3.K3Application;
import com.lgmshare.component.utils.ContextUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * <p>Title: UpgradeManager</p>
 * <p>Description: app更新下载管理</p>
 *
 * @author LGM
 * @mail lgmshare@gmail.com
 * @date 2014-5-14下午09:09:20
 */
public class UpgradeManager {

    interface UpdateShared {
        String SETTING_UPDATE_APK_INFO = "cbt_upgrade_setting";
        String UPDATE_DATE = "updatedate";
        String APK_VERSION = "apkversion";
        String APK_VERCODE = "apkvercode";
        String CHECK_DATE = "checkdate";
    }

    private static final int CHECK_UPDATE_DAY = 1;

    private Context mContext;

    private ProgressDialog mProgressDialog; //手动检查等待框

    private boolean mDownloading = false;
    private boolean mAccord = false;// 是否主动检查软件升级（主动检查会给出提示）
    private Handler mHandler;
    private UpgradeVersion mUpgradeVersion;

    /**
     * 检查更新，
     *
     * @param context
     * @param isAccord 是否同步显示更新检测
     */
    public void checkUpdate(Context context, boolean isAccord) {
        if (mDownloading) {
            Toast.makeText(mContext, "正在下载更新版本。", Toast.LENGTH_LONG).show();
            return;
        }
        this.mContext = context;
        this.mAccord = isAccord;
        this.mHandler = new CheckHandler();
        if (!NetworkUtils.isConnected(mContext)) { // 检查网络连接是否正常
            mHandler.sendEmptyMessage(CheckHandler.CHECK_NETFAIL);
        } else if (checkTodayUpdate() || mAccord) {// 判断今天是否已自动检查过更新 ；如果手动检查更新，直接进入
            httpRequestCheckUpdate();
        }
    }

    /**
     * 弹出软件更新提示对话框
     */
    private void showNoticeDialog() {
        UpgradeDialogFragment updateFragment = UpgradeDialogFragment.newInstance(mUpgradeVersion.getVersion(), mUpgradeVersion.getDownloadUrl(), mUpgradeVersion.getApkLog(), mUpgradeVersion.isForceUpdate());
        updateFragment.setUpdateListener(new UpgradeDialogFragment.UpdateListener() {
            @Override
            public void onUpdate() {
                new UpgradeDownloadManger(mContext, mUpgradeVersion.getDownloadUrl()).startDownloadApk();
            }

            @Override
            public void onCancel() {

            }
        });
        updateFragment.setCancelable(!mUpgradeVersion.isForceUpdate());
        updateFragment.show(K3Application.getInstance().getCurrentActivity().getFragmentManager(), "updateFragment");
    }

    /**
     * 进度窗口
     */
    private void showProgressDialog() {
        try {
            mProgressDialog = ProgressDialog.show(mContext, "", "请稍后，正在检查更新...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissProgressDialog() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void httpRequestCheckUpdate() {
       /* CommonTask.Upgrade task = new CommonTask.Upgrade();
        task.setCallback(new SimpleCallback<UpgradeVersion>() {

            @Override
            public void onStart() {
                super.onStart();
                //主动检查更新提示
                if (mAccord) {
                    showProgressDialog();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (mAccord) {
                    dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(int statusCode, String error) {
                mHandler.sendEmptyMessage(CheckHandler.CHECK_FAIL);
            }

            @Override
            public void onSuccess(UpgradeVersion config) {
                mUpgradeVersion = new UpgradeVersion();
                mUpgradeVersion.setVersionCode(config.getVersionCode());
                mUpgradeVersion.setVersion(config.getVersion());
                mUpgradeVersion.setForceUpdate(config.isForceUpdate());
                mUpgradeVersion.setDownloadUrl(config.getDownloadUrl());
                mUpgradeVersion.setApkLog(config.getApkLog());
                if (mUpgradeVersion != null && checkApkVersionCode()) { // 检查版本号
                    if (!mUpgradeVersion.isForceUpdate) {
                        // 不是强制更新，允许推迟更新
                        checkedTodayUpdate();// 设置今天已经检查过更新
                    }
                    mHandler.sendEmptyMessage(CheckHandler.CHECK_SUCCESS);
                } else {
                    checkedTodayUpdate(); // 设置今天已经检查过更新
                    mHandler.sendEmptyMessage(CheckHandler.CHECK_NOUPGRADE);
                }
            }

        });
        task.sendPost(this);*/
    }

    /**
     * 根据日期检查是否需要进行软件升级
     */
    private boolean checkTodayUpdate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        SharedPreferences sharedPreference = mContext.getSharedPreferences(UpdateShared.SETTING_UPDATE_APK_INFO, 0);
        String checkDate = sharedPreference.getString(UpdateShared.CHECK_DATE, "");
        String updateDate = sharedPreference.getString(UpdateShared.UPDATE_DATE, "");
        if ("".equals(checkDate) && "".equals(updateDate)) { // 刚安装的新版本，设置详细信息
            int verCode = ContextUtils.getVersionCode(mContext);
            String versionName = ContextUtils.getVersionName(mContext);
            String dateStr = sdf.format(new Date());
            sharedPreference.edit().putString(UpdateShared.CHECK_DATE, dateStr)
                    .putString(UpdateShared.UPDATE_DATE, dateStr)
                    .putString(UpdateShared.APK_VERSION, versionName)
                    .putInt(UpdateShared.APK_VERCODE, verCode).commit();
            return true;
        }
        try {
            // 判断defaultMinUpdateDay天内不检查升级
            if ((System.currentTimeMillis() - sdf.parse(updateDate).getTime()) / 1000 / 3600 / 24 < CHECK_UPDATE_DAY) {
                return false;
            } else if (checkDate.equalsIgnoreCase(sdf.format(new Date()))) {// 判断今天是否检查过升级
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 设置今天已经检查过升级
     *
     * @return
     */
    private void checkedTodayUpdate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String date = sdf.format(new Date());
        SharedPreferences sharedPreference = mContext.getSharedPreferences(UpdateShared.SETTING_UPDATE_APK_INFO, 0);
        sharedPreference.edit().putString(UpdateShared.CHECK_DATE, date).commit();
    }

    /**
     * 检查版本是否需要更新
     *
     * @return
     */
    private boolean checkApkVersionCode() {
        return mUpgradeVersion.getVersionCode() > ContextUtils.getVersionCode(mContext);
    }

    /**
     * 更新检查提示
     */
    @SuppressLint("HandlerLeak")
    private class CheckHandler extends Handler {

        final static int CHECK_FAIL = 0;
        final static int CHECK_SUCCESS = 1;
        final static int CHECK_NOUPGRADE = 2;
        final static int CHECK_NETFAIL = 3;

        public void handleMessage(android.os.Message msg) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            switch (msg.what) {
                case CHECK_SUCCESS: {
                    showNoticeDialog();
                    break;
                }
                case CHECK_NOUPGRADE: { // 不需要更新
                    if (mAccord)
                        Toast.makeText(mContext, "当前版本是最新版。", Toast.LENGTH_LONG).show();
                    break;
                }
                case CHECK_NETFAIL: {
                    if (mAccord)
                        Toast.makeText(mContext, "网络连接不正常。", Toast.LENGTH_LONG).show();
                    break;
                }
                case CHECK_FAIL: {
                    if (mAccord)
                        Toast.makeText(mContext, "从服务器获取更新数据失败。", Toast.LENGTH_LONG).show();
                    break;
                }
            }
        }
    }
}
